package com.zhuang.controller;

import com.zhuang.dto.ImageUploadDTO;
import com.zhuang.dto.ResultDTO;
import com.zhuang.exception.CustomizeErrorCode;
import com.zhuang.exception.CustomizeException;
import com.zhuang.utils.QiniuCloudUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
public class ImageUploadController {

    @RequestMapping(value = "/image/upload")
    @ResponseBody
    public ImageUploadDTO upload(HttpServletRequest request) {  //
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("editormd-image-file");
        if (file.isEmpty()) {
            ImageUploadDTO imageUploadDTO = new ImageUploadDTO();
            imageUploadDTO.setSuccess(0);
            imageUploadDTO.setMessage("上传失败");
            return  imageUploadDTO;
        }
        try {
            byte[] bytes = file.getBytes();
            String urlName = UUID.randomUUID().toString();
            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            String url = qiniuUtil.put64image(bytes, urlName);
            url = url.replace("qseoqy0p2.hn-bkt.clouddn.com", "qseoqy0p2.hn-bkt.clouddn.com/");
            System.out.println(url);
            ImageUploadDTO imageUploadDTO = new ImageUploadDTO();
            imageUploadDTO.setSuccess(1);
            imageUploadDTO.setMessage("上传成功");
            imageUploadDTO.setUrl("http://"+url);
            return imageUploadDTO;
        } catch (Exception e) {
            throw new CustomizeException(CustomizeErrorCode.IMAGE_UPLOAD_ERROR);
        }


    }
}
